package com.cy;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@EnableFeignClients
@SpringBootApplication
public class ScaConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScaConsumerApplication.class,args);
    }
    @Service
    public class ConsumerService{
        @SentinelResource("doConsumerService")
        public String doConsumerService(){
            return "do consumer service";
        }
    }
    /*spring boot 工程中可以使用此对象调用第三方服务*/
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedRestTemplate(){return new RestTemplate();}
    @RestController
    public class ConsumerContorller{
        @Autowired
        private ConsumerService consumerService;
        @Value("${spring.application.name}")
        private String consumerName;
        @Autowired
        private RestTemplate restTemplate;
        @Autowired
        private RestTemplate loadBalancedRestTemplate;
        @RequestMapping("/consumer/doEcho01")
        public String toEcho01(){
            String url="http://localhost:8081/provider/echo/"+consumerName;
            return restTemplate.getForObject(url,String.class);
        }
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @RequestMapping("/consumer/doEcho02")
        public String toEcho02(){
            ServiceInstance choose = loadBalancerClient.choose("sca-provider");
            String ip = choose.getHost();
            int port = choose.getPort();
           // String url="http://"+ip+":"+port+"/provider/echo/"+consumerName;
            String url = String.format("http://%s:%s/provider/echo/%s", ip, port, consumerName);
            return restTemplate.getForObject(url,String.class);
        }
        @RequestMapping("/consumer/doEcho03")
        public String toEcho03(){
            consumerService.doConsumerService();
            String url = String.format("http://%s/provider/echo/%s","sca-provider", consumerName);
            return loadBalancedRestTemplate.getForObject(url,String.class);
        }
    }
}
